function sel_tab(id)
{
    for (var i=1; i<=7; i++)
    {
        // 关闭所有节目单
        var obj = document.getElementById('week_' +　i);
        obj.className = "close";
        // 清空所有选项卡的样式
        obj = document.getElementById('tab_' +　i);
        obj.className = "";
    }
    // 开启选中的节目当
    obj = document.getElementById('week_' +　id);
    obj.className = "";
    // 选中的选项卡赋予active样式，即选中状态
    obj = document.getElementById('tab_' +　id);
    obj.className = "active";
}

function sel_menu(id)
{
    $('.inner').attr('class', 'inner close');
    $('#menu_' + id).attr('class', 'inner');
}

/**
 * @author zen
 */
//设为首页&加入收藏
var isIE6=$.browser.version==6&&$.browser.msie;
if (isIE6) {
    document.execCommand("BackgroundImageCache", false, true);  //IE6下缓存背景图
}
var IndexSearchTool = function(){
    var url = TOOL_URL + '/index/search';
    url += '/q/' + encodeURIComponent(document.getElementById('search_kw').value);
    window.location.href=url;
} 

$(document).ready(function(){
	
    
    //头部导航
    headerNav();
    
    $('.js_keyword_box:first').focus();
    
    /*查询记录开始*/
    try{
        if(Sidebar_History){
            Sidebar_History.ClickHandler = function(pValue){
                $(".js_keyword_box:first").val(pValue);
                $('.js_keyword_box:first').parents('form').submit(); 
            };
        }
    }catch(e){}
    
    $('form.js_search_form').submit(function() {
        var obj_keyword_box = $(this).find('.js_keyword_box');
        var value = obj_keyword_box.val().replace(/^https?:\/\//i, '');
        if (value != '') {
            if ($(this).attr('rewrite') == '1') {
                var url = $(this).find('.js_tool_url').val() + '/' + value;
            } else {
                var url = $(this).find('.js_tool_url').val() + '/' + obj_keyword_box.attr('name') + '/' + value;
            }
            window.location.href = url;
            
            try{
                if(Sidebar_History){
                    Sidebar_History.Set(value);
                }
            }catch(e){}
        } else {
            obj_keyword_box.focus();
        }
        return false;
    });
    
    Handle_Bar_Search_URL = window.location.href;
    var ele = $("#js_handle_add");
    var tool_Id = ele.attr("rel");
    ShowDelBtn(tool_Id);
    ele.bind("click",function(){
        if(Public.MyTools.Set(tool_Id) == 1){
            PageResult.Show("成功添加到我的工具",true);
        }
        else{
            PageResult.Show("已添加过此工具",false);
        }
        ShowDelBtn(tool_Id);
    });
    $("#js_handle_dele").bind("click",function(){
        if(Public.MyTools.Delete(tool_Id) == 1){
            PageResult.Show("移除成功",true);
        }
        else{
            PageResult.Show("我的工具中没有这个工具",false);
        }
        ShowDelBtn(tool_Id);
    });
    
    googleHot();
});

//头部下拉导航
var headerNav=function(){
    var live=$("#list_live"),site=$("#list_site"),code=$("#list_code"),subHeader=$("#sub_header");
    var Datas={
        "live":[["tianqi","天气预报"],["live/huoche","列车时刻表"],["live/speed","网速测试"],["bus","公交查询"],["shouji","手机号码归属地查询"],["live/caipiao","彩票查询"],["live/calendar","万年历"],["live/idcard","身份证归属地查询"],["ip","IP地址查询"],["live/fanyi","免费在线翻译"],["history/","历史上的今天"],["live/menses","女性安全期测算"],["live/express","快递查询"],["youbian","邮编区号查询"],["live/nongli","黄道吉日查询"],["finance/rate","汇率查询"],["live/qqtouxiang","QQ头像在线制作"],["live/nannv","生男生女预测"],["live/body","体质指数|体重标准"],["live/phone","常用电话号码"],["live/car","车辆违章查询"],["live/chepai","车牌号码查询"],["live/herb","中药大全"],["live/huoxingwen","火星文转换"],["live/food","食物热量查询"],["live/ditu","世界地图"],["live/renpinjisuanqi","人品计算器"],["live/weibo","QQ微博邀请码"],["live/tuya","在线涂鸦PS"],["live/zhengshu","毕业证书生成器"]],
        "site":[["alexa","Alexa网站排名"],["pr","PR值查询"],["whois","Whois查询"],["siteall","网站综合查询"],["sitespeed","网站反应速度测试"],["record","网站收录查询"],["link","友情链接检测"],["sameip","相同IP网站查询"],["site/wapview","在线WAP模拟器"],["site/meta","网站META信息查看"],["site/html","HTML源代码查看器"],["site/header","网站Header查看"]],
        "code":[["site/zhuantie","超级转帖工具"],["site/html2js","HTML/JS互转"],["site/html2ubb","HTML/UBB互转"],["site/utf8","UTF-8编码转换工具"],["site/htmlformat","JS代码格式工具"],["site/escape","escape加密解密"],["site/regular","正则表达式检测"],["site/highlight","代码语法高亮工具"],["site/webdebug","网页代码调试器"],["site/effect","多彩特效字生成器"],["site/buildmeta","META标签生成器"],["site/ascii","ASCII字形生成器"],["site/str2asc","字符串转ASCII"],["code/measures","单位换算查询"],["code/jisuanqi","智能计算器"],["code/urlconvert","下载地址转换"]]
    }
    var codeHTML=function(type){
        var html=[];
        var arg=Datas[type];
        for(var i=0,j=arg.length;i<j;i++){
            html.push('<span><a href="/');
            html.push(arg[i][0]);
            html.push('/" target="_blank">');
            html.push(arg[i][1]);
            html.push('</a></span>');
        }
        html.push('<span class="sub-more">X</span>');
        return html.join("");
    }
    var init=function(){
        if(CATE_ID===""){
            live.html(codeHTML("live"));
            site.html(codeHTML("site"));
            code.html(codeHTML("code"));
            new tab_content(
                [
                    {TabId:"nav_live",ContentId:"list_live"},
                    {TabId:"nav_site",ContentId:"list_site"},
                    {TabId:"nav_code",ContentId:"list_code"}
                ],"current"
            );
            subHeader.find(".sub-more").click(function(){
                $(this).parent().hide();
                $(live,site,code).removeClass("current");
            });
        }else{
            subHeader.find("input.text").val("").focus(function(){
                $(this).prev().hide();
            }).blur(function(){
                if(this.value===""){
                    $(this).prev().show();
                }else{
                    $(this).prev().hide();
                }
            });
        }
    }();
}


/*收藏工具箱*/
var bookmarkname='114啦工具箱';
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
}
function addBookmark(title,url) {
    if( document.all ) {
        window.external.AddFavorite( url, title);
    }else if (window.sidebar) {
        window.sidebar.addPanel(title, url,"");
    }else if( window.opera && window.print ) {
        return true;
    }
}
/*设置主页*/
function setHomePage(url){
    if (window.sidebar) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } 
        catch (e) {
            alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'");
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', url);
    }
}

/*Tab菜单切换*/
var tab_content = function(pBtnList,pActiveStyle,pDisableStyle){
	var _obj = {
		List: pBtnList,
		ActiveStyle: pActiveStyle,
		DisableStyle: pDisableStyle
	};
	var _ChangeHandler;
	var time ;
	var overObj;
	function display(){
		for(var j = 0; j < _obj.List.length; j++){
			var ele = $("#" +  _obj.List[j].TabId);
			ele.removeClass(_obj.ActiveStyle);
			ele.addClass(_obj.DisableStyle);
			$("#" + _obj.List[j].ContentId).hide();
		}
		$("#" + overObj.TabId).addClass(_obj.ActiveStyle);
		$("#" + overObj.ContentId).show();
		if(_ChangeHandler){
			_ChangeHandler(overObj);
		}
	}
	
	var init = function(){
		for(var i = 0; i < _obj.List.length; i++){
			var item = _obj.List[i];
			$("#" + item.TabId).bind("mouseover",item,function(e){
				overObj = e.data;
				time = window.setTimeout(display,400);
			});
			$("#" + item.TabId).bind("click",item,function(e){
				overObj = e.data;
				if(time != undefined){
					window.clearTimeout(time);
				}
				display();
				this.blur();
			});
			$("#" + item.TabId).bind("mouseout",function(){
				if(time != undefined){
					window.clearTimeout(time);
				}
			});
		}
	}
	this.SetChangeHandler = function(pHandler){
		_ChangeHandler = pHandler;
	}
	this.Select = function(key){
		overObj = _obj.List[key];
		display();
	}
	init();
}

var PageResult = {TimeOut:4000};
PageResult.Show = function(msg,isSuccess,timeOut,isHide){
	if(PageResult.ControlObject == undefined){
		PageResult.ControlObject = new PageResult.ShowResultObject({
            //Top:"150px"
			Top:"0"
		});
	}
    PageResult.ControlObject.ShowMessage(msg,isSuccess);
	var time = PageResult.TimeOut;
	if(timeOut){
		time = timeOut
	}
	if(isHide == undefined || isHide == true){
		window.clearTimeout(PageResult.Timer);
    	PageResult.Timer = window.setTimeout("PageResult.Hide()",time);
	}
}

PageResult.Hide = function(){
	PageResult.ControlObject.Hide();
	window.clearTimeout(PageResult.Timer);
}

/**
 * 显示结果静态方法
 * ResultControl.TimeOut = 4000;	//设置信息隐藏时间
 * ResultControl.Show(msg,isSuccess); //(msg: 内容; isSuccess： true成功操作，false失败操作)
 */
PageResult.ShowResultObject = function(obj){
    var _ResultBpx;
	var _obj = obj == undefined?{}:obj;
    var _DisplayTextBox;
    if(_obj.BoxID !=undefined){
        _ResultBpx = document.getElementById(_obj.BoxID);
    }
    else{
        _ResultBpx = document.createElement("div");
        document.body.appendChild(_ResultBpx);
    }
    if(_obj.DisplayBoxId != undefined){
        _DisplayTextBox = document.getElementById(_obj.DisplayBoxId);
    }
    else{
        _DisplayTextBox = document.createElement("span");
        _ResultBpx.appendChild(_DisplayTextBox);
    }

    var setStyle = function(isPerfect){
        _DisplayTextBox.style.color = isPerfect?"#48A01B" : "#FF0000";
        var  resultStyle = _ResultBpx.style;
        resultStyle.backgroundColor =  "#FFF8CC";
        resultStyle.position = "absolute";
        resultStyle.zIndex = 1000;
        resultStyle.padding = "1px 6px";
        var l = document.documentElement.clientWidth * 44/100;
        resultStyle.left = _obj.Left == undefined? (l + "px") : _obj.Left;
		resultStyle.top = _obj.Top == undefined? "0px" : _obj.Top;
    }

    this.getResultBox = _ResultBpx;
    this.getDisplayBox = _DisplayTextBox;
    this.Hide = function(){
        this.getResultBox.style.display = "none";
		this.getDisplayBox.innerHTML =  "";
    }
    this.ShowMessage = function(text,isSuccess){
        setStyle(isSuccess);
        this.getDisplayBox.innerHTML = text;
        this.getResultBox.style.display = "";
    }
}

Function.prototype.bindevent = function(scope, args){
		var method = this;
		if(args === undefined){
			args = [];
		}
		return function() {
			return method.apply(scope, args.concat(arguments));
		}
	}

/**
 * TextBox 提示
 */
var TextBoxDrop = function(pInputId,pContentId){
	var _self = this;
	var _EnterHandler;
	var _AjaxMethod;
	var _input = document.getElementById(pInputId);;
	var _ContentBox = document.getElementById(pContentId);
	var _Data;
	var _activeItemStyle = "active";
	var _activeId = -1;
	var _mouseInContent = false;
	var _DisplayContentHandler;	//显示事件
	var _SetContentStyle;
	var _url = "";	//查询地址
	var _oldStr = "";	
	var _timer;
	var _oldData;
	this.GetUrlHandler;
	this.KeyFeild;
	this.TextFeild;

	var bindevents = function(){
		_input.onkeyup = keyUpFun;
		_input.onkeydown = keyDownFun;
		_input.onfocus = function(){
			_input.select();
			getDataFun();
		};
		_input.onblur = function(){
			clearTimer();
			if(!_mouseInContent){
				hideBox();
			}
		};
		_ContentBox.onmousemove = function(){
			_mouseInContent = true;
		};
		_ContentBox.onmouseout = function(){
			_mouseInContent = false;
		};
	}
	
	/*Event*/
	this.ActiveItem;
	var keyDownFun = function(e){
		var key = window.event ? event.keyCode : e.which;
		switch(key){
			case 13:
				if(!isHiden()){
					clearTimer();
					hideBox();
				}
				else{
					return true;
				}
				if(_EnterHandler){
					_EnterHandler(_input.value);
				}
				//Enter
				return false;
			case 40:
				//Down
				_activeId += 1;
				hoverItem();
				return;
			case 38:
				//UP
				_activeId -= 1;
				hoverItem();
				return;
		}
	}
	
	var keyUpFun = function(e){
		var key = window.event ? event.keyCode : e.which;
		switch(key){
			case 13:
				if(!isHiden()){
					clearTimer();
					hideBox();
				}
				else{
					return true;
				}
				return false;
			case 40:
				return;
			case 38:
				return;
			default:
				_activeId = -1;
				getDataFun();
				break;
		}
	}

	var clearTimer = function(){
		if(_timer){
			window.clearTimeout(_timer);
			_timer = null;
		}
	}
	
	/*/Event*/
	var getDataFun = function(){
		clearTimer();
		_timer = window.setTimeout(searchFun,400);
	}
	
	var searchFun = function(){
		if(_input.value != ""){
			if(_oldStr != _input.value.trim() || _oldStr == ""){
				var url = _url + encodeURIComponent(_input.value.trim());
				if(_self.GetUrlHandler){
					url = _self.GetUrlHandler();
				}
				if(_AjaxMethod){
					_oldStr = _input.value.trim();
					_AjaxMethod(url,function(data){
						var arr = eval(data);
						_oldData = arr;
						if(arr && arr.length > 0){
							showBox();
							displayContent(arr);
						}
						else{
							hideBox();
						}
					});
				}
			}
			else{
				if(_oldData && _oldData.length > 0){
					showBox();
					displayContent(_oldData);
				}
			}
		}
		else{
			_oldStr = "";
			hideBox();
		}
	}
	
	var hoverItem = function(){
		var liArr = _ContentBox.getElementsByTagName("li");
		if(_activeId > liArr.length-1){
			_activeId = 0;
		}
		if(_activeId < 0){
			_activeId = liArr.length-1;
		}
		for(var i = 0; i < liArr.length; i++){
			var item = liArr[i];
			if(i == _activeId){
				item.className = _activeItemStyle;
				setInputValue(item);
				_self.ActiveItem = item;
			}
			else{
				item.className = "";
			}
		}
	}
	
	var setInputValue = function(ele){
		if(_isArray){
			_input.value = ele.innerHTML;
		}
		else{
			
			if(_self.ShowKey){
				_input.value = ele.getAttribute("rel");
			}
			else{
				_input.value = ele.innerHTML;
			}
		}
	}
	
	this.ShowKey = false;
	var _isArray = true;
	var displayContent = function(arr){
		var html = "";
		if(_activeId > arr.length-1){
			_activeId = arr.length-1;
		}
		if(_activeId < -1){
			_activeId = -1;
		}
		_ContentBox.innerHTML = "";
		_self.ActiveItem = null;
		for(var i = 0; i < arr.length; i++){
			var item = document.createElement("li");
			if(typeof arr[i] == "string"){
				item.innerHTML = arr[i];
				_isArray = true;
			}
			else if(typeof arr[i] == "object"){
				if(_self.KeyFeild){
					item.innerHTML = arr[i][_self.TextFeild];
					item.setAttribute("rel",arr[i][_self.KeyFeild]);
				}
				_isArray = false;
			}
			item.onmouseover = mOver.bindevent(this,[item]);
			item.onmouseout = mOut.bindevent(this,[item]);
			item.onclick = mClick.bindevent(this,[item]);
			_ContentBox.appendChild(item);
		}
		if(_DisplayContentHandler){
			_DisplayContentHandler(_input,_ContentBox);
		}
		if(_SetContentStyle){
			_SetContentStyle(_input,_ContentBox);
		}
	}
	
	var mOver = function(ele){
		_activeId = -1;
		ele.className = _activeItemStyle;
	}
	
	var mOut = function(ele){
		ele.className = "";
	}
	
	var mClick =  function(ele){
		 setInputValue(ele);
		 _self.ActiveItem = ele;
		 if(_EnterHandler){
			_EnterHandler(_input.value);
		 }
		 
		 hideBox();
	}
	
	var isHiden = function(){
		return _ContentBox.style.display == "none";
	}
	
	var showBox = function(){
		_ContentBox.style.display = "block";
	}
	
	var hideBox = function(){
		_ContentBox.style.display = "none";
		_ContentBox.innerHTML = "";
	}

	var init = function(){
		bindevents();
	}
	
	this.SetEnterHandler = function(pHandler){
		_EnterHandler = pHandler;
	}
	this.SetAjaxMethod = function(pMethod){
		_AjaxMethod = pMethod;
	}
	this.SetContentStyle = function(callback){
		if(callback){
			_SetContentStyle = callback;
			_SetContentStyle(_input,_ContentBox);
		}
	}
	this.DisplayContentHandler = function(pHandler){
		_DisplayContentHandler = pHandler;
	}
	this.Url = function(pUrl){
		if(pUrl){
			_url = pUrl;
		}
	}
	init();
}

//提示框加提示信息
var Common_SetInputTips = function(box_id,text){
	var box = document.getElementById(box_id);
	
	var isHasValue = function(){
		return box.value != text;
	}
	
	box.rel=false;
	if(box.value == ""){
		box.value = text;
		box.style.color = "#ccc";
	}
	else{
		if(isHasValue()){
			box.style.color = "#000";
			box.rel = true;
		}
		else{
			box.style.color = "#ccc";
		}
	}
	
	box.getValue = function(){
		if(isHasValue()){
			return box.value;
		}
		else{
			return '';
		}
	}
	box.onfocus = function(){
		box.style.color = "#000";
		if(box.value == text){
			box.value = '';
			box.rel = false;
		}
		else{
			box.rel = true;
		}
	}
	box.onblur = function(){
		if(box.value == ""){
			box.value = text;
			box.style.color = "#ccc";
		}
		else{
			box.rel = true;
		}
	}
	return box;
}

var Public = {};


/*
* 
* 验证身份证格式
* return 1 正确; 0日期有误; -1 18位的格式有误; -2 15位的包含有非数字字符; -3 18位包含的字符不正确; -4 字符不够
*/
Public.ValidateIdentityCard = function(pNumber){
    var error = 1;
    pNumber = pNumber.toUpperCase();
    var l = pNumber.length;
    switch(l){
        case 15:
            if(/^\d{15}$/.test(pNumber)){
                var year = '19' + pNumber.substring (6, 8 );
                var month = pNumber.substring (8, 10 );
                var day = pNumber.substring (10, 12 );
                if(!Public.CheckDate(Number(year),Number(month),Number(day))){
                    error = 0;
                }
            }
            else{
                error = -2;
            }
            break;
        case 18:
            if(/^\d{17}(\d|X)$/.test(pNumber)){
                var year = pNumber.substring(6, 10);
                var month = pNumber.substring(10, 12 );
                var day = pNumber.substring(12, 14);
                if(Public.CheckDate(Number(year),Number(month),Number(day))){
                    var sigma = 0;
                    var st = pNumber.substring (0, pNumber.length-1);
                    var wi = new Array (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 );
                    var ai = new Array ('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' );
                    var _st,_wi;
                    for(var i = 0; i < 17; i++)
                    {
                        _st =  st.substring(i,i+1);
                        _wi = wi [i];
                        sigma += (Number(_st) * _wi);
                    }
                    if ((pNumber.substring(pNumber.length-1)) != ai [sigma % 11]){
                        error = -1;
                    }
                }
                else{
                    error = 0;
                }
            }
            else{
                error = -3;
            }
            break;
        case 6:
            if(!(/^\d{6}$/.test(pNumber))){
                error = -5;
            }
            break;
        default:
            error = -4;
            break;
    }
    return error;
}

/*
* 
* 验证URL
* return true 正确; false 错误
*/
Public.ValidateUrl = function(pUrl){
    var str_url = pUrl;
    var regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i
    if(regular.test(str_url)){
        return true;                                                                                                                                                                                                                                    }
    else{
        return false; 
    }
}

/*
* 
* 验证手机号码
* return 1 正确; 0手机号有误;
*/
Public.ValidateMoblie = function(pNumber){
    var l = pNumber.length;
    var error = 1;
    switch(l){
        case 7:
            if(!/^(13[0-9]|15[0-9]|14[0-9]|18[7|8|9|6|5|2])\d{4}$/.test(pNumber)){
                error = 0;
            }
            break;
        case 11:
            if(!/^(13[0-9]|15[0-9]|14[0-9]|18[7|8|9|6|5|2])\d{4,8}$/.test(pNumber)){
                error = 0;
            }
            break;
        default:
            error = -1;
            break;
    }
    return error;
}

Public.ValidateChinaChar = function(pChar){
    if(!/^[\u4e00-\u9fa5\s]+$/.test(pChar)){
        return false;
    }
    return true;
}

/*
* 
* 验证邮编
* return true 正确;false有误;
*/
Public.ValidateZip = function(pNumber){
    if(!/^(\d{3,6})$|^([\u4e00-\u9fa5\s]{2,})$/.test(pNumber)){
        return false;
    }
    return true;
}

/*
* 
* 验证日期格式
* return True 正确； False 错误；
*/
Public.CheckDate = function (year, month, day ) {
    var myDate = new Date();
    myDate.setFullYear( year, (month - 1), day );
    return ((myDate.getMonth()+1) == month && day<32); 
}

/*
* 
* 复制
*/
Public.Copy = function(pStr, msg){
    //IE            
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("Text", pStr);
    // FireFox
    } else if (navigator.userAgent.indexOf("Firefox") > 0) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } 
        catch (e) {
            alert("您的 Firefox 安全限制限制您进行剪贴板操作，请打开 'about:config' 将 'signed.applets.codebase_principal_support' 设置为 'true' 之后重试");
            return false;
        }
        var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) 
            return;
        var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
        if (!trans) 
            return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext = pStr;
        str.data = copytext;
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip) 
            return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
    } else {
    	alert('您使用的浏览器不支持此复制功能，请使用 Ctrl + C 或鼠标右键。');
    }
    var showMsg = msg ? msg : "内容已复制到剪切板！";
    alert(showMsg);
}

/*
* 
* 字符串控制
*/
Public.String = {};
Public.String.HtmlSpecialChars = function(string){
    var data = [];
    for(var i = 0 ;i <string.length;i++) {
        data.push( "&#"+string.charCodeAt(i)+";");
    }
    return data.join("");
}
Public.String.Cut = function(str, str_long) {
    str = str.trim();
    if (str.length <= (str_long + 1)) {
        return Public.String.HtmlSpecialChars(str);
    } else {
        return str.substring(0, str_long) + "..";
    }
}

/*
* 
* 历史记录
*/
Public.History = {};
Public.History.length = 10;
Public.History.Set = function(pKey,value){
    value = value.trim();
    //value = value.trim();
    var hisCol = Public.History.Get(pKey);
    if(hisCol.length > 0){
        var index = -1;
        for(var i = 0; i < hisCol.length; i++){
            if(hisCol[i] == value){
                index = i;
            }
        }
        if(index > -1){
            hisCol.splice(index,1);
        }
        else{
            var l = hisCol.length;
            if(l == Public.History.length){
                hisCol.splice(0,1);
            }
        }
        hisCol.push(value);
        Public.Cookie.Set("history_" + pKey,hisCol.toString(),24);
    }
    else{
        Public.Cookie.Set("history_" + pKey,value,24);
    }
}
Public.History.Get = function(pKey){
    var name = "history_" + pKey;
    var c = Public.Cookie.Get(name);
    var hisCol;
    if(c != ""){
        hisCol = c.split(',');
    }
    else{
        hisCol = [];
    }
    return hisCol;
}
Public.History.Clear = function(pKey){
    Public.Cookie.Set("history_" + pKey,'');
}

Public.MyTools = {};
Public.MyTools.cookie_name = MY_TOOLS_COOKIE;
Public.MyTools.IsExist = function(pToolId){
    var result = -1;
    var name = Public.MyTools.cookie_name;
    var v = Public.Cookie.Get(name);
    var col;
    if(v != ""){
        col = v.split(',');
    }
    else{
        col = [];
    }
    for(var i = 0; i < col.length; i++){
        if(col[i] == pToolId){
            result = i;
            break;
        }
    }
    return result;
}

Public.MyTools.Set = function(pToolId){
    var name = Public.MyTools.cookie_name;
    var i = Public.MyTools.IsExist(pToolId);
    var LACK1 = Public.Cookie.Get("LACK1"); //用户信息, add by alex 2010-2-3
    var exist = (i != -1);
    var state = 1;
    if(!exist){
        var v = Public.Cookie.Get(name);
        var col;
        if(v != ""){
            col = v.split(',');
        }
        else{
            col = [];
        }
        col.push(pToolId);
        Public.Cookie.Set(name,col.toString(),30*24);
        if(LACK1 != ''){
            Public.Cookie.Set("tools_my_change",'1',30*24);
        }
        
        Public.MyTools.Save();
    }
    else{
        state = 0;
    }
    return state;
}

Public.MyTools.Delete = function(pToolId){
    var name = Public.MyTools.cookie_name;
    var index = Public.MyTools.IsExist(pToolId);
    var LACK1 = Public.Cookie.Get("LACK1"); //用户信息, add by alex 2010-2-3
    if(index != -1){
        var v = Public.Cookie.Get(name);
        var col;
        if(v != ""){
            col = v.split(',');
        }
        else{
            col = [];
        }
        col.splice(index,1);
        Public.Cookie.Set(MY_TOOLS_COOKIE,col.toString(),30*24);
        if(LACK1 != ''){
            Public.Cookie.Set("tools_my_change",'1',30*24);
        }
        Public.MyTools.Save();
        return 1;
    }
    else{
        return 0;
    }
}
Public.MyTools.Save = function() {
	var tools = Public.Cookie.Get(Public.MyTools.cookie_name);
	var url_prefix = TOOL_URL ? TOOL_URL : '';
	if (Public.Cookie.Get("LACK1") != '') {
		$.ajax({
			url: url_prefix + '/index/tools_my',
			data: "tools="+tools,
			type: "POST",
			cache: false,
			success: function(result) {}
		}); 
	}    
}

/*
* 
* Cookie 控制
*/
Public.Cookie = {};
Public.Cookie.Set = function(name, value, hours){
  var expire = new Date((new Date()).getTime() + 3600000*24*365);
  if(hours != null){
    expire = new Date((new Date()).getTime() + hours * 3600000);
  }
  expire = "; expires=" + expire.toGMTString();
  document.cookie = name + "=" + escape(value) + expire + '; path=/';
}

Public.Cookie.Get = function(name){
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0){ 
    offset = document.cookie.indexOf(search);
    if (offset != -1){ 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}

/*
* 
* 别人正在查，翻页
*/
Public.BoxDisplayControl = function(obj){
    var _obj = obj;
    var _pageCol = [];

    var bindingEvent = function(){
        _obj.PreBox.bind("click",function(){
            if(_obj.ActiveStep > 0 && _cutState){
                endCorss();
                _obj.ActiveStep -= 1;
                display();
                startCorss();
            }
        });
        _obj.NextBox.bind("click",function(){
            if(_obj.ActiveStep < _pageCol.length - 1 && _cutState){
                endCorss();
                _obj.ActiveStep += 1;
                display();
                startCorss();
            }
        });
    }
    
    var _cutState = true;

    var display = function(pFast){
        if(_pageCol.length > 0){
            displayBtn();
            for(var i = 0; i < _pageCol.length; i++){
                _pageCol[i].hide();
            }
            _cutState = false;
            if(pFast){
                _pageCol[_obj.ActiveStep].show();
                _cutState = true;
            }
            else{
                _pageCol[_obj.ActiveStep].show("slow",function(){
                    _cutState = true;
                });
            }
        }
    }
    
    var displayBtn = function(){
        if(_obj.ActiveStep > 0){
            _obj.PreBox.addClass(_obj.PreStyle);
            _obj.PreBox.removeClass(_obj.PreDisableStyle);
        }
        else{
            _obj.PreBox.addClass(_obj.PreDisableStyle);
            _obj.PreBox.removeClass(_obj.PreStyle);
        }
        
        if(_obj.ActiveStep < _pageCol.length - 1){
            _obj.NextBox.addClass(_obj.NextStyle);
            _obj.NextBox.removeClass(_obj.NextDisableStyle);
        }
        else{
            _obj.NextBox.addClass(_obj.NextDisableStyle);
            _obj.NextBox.removeClass(_obj.NextStyle);
        }
    }
    
    var corssPage = function(){
        if(_cutState){
            _obj.ActiveStep++;
            if(_obj.ActiveStep > _pageCol.length - 1){
                _obj.ActiveStep = 0;
            }
            display();
        }
    }
    
    var _timer;
    var startCorss = function(){
        if(_pageCol.length > 1){
            _timer = window.setInterval(corssPage,4000);
        }
    }
    
    var endCorss = function(){
        if(_pageCol.length > 1){
            window.clearInterval(_timer);
        }
    }
    
    this.AddPageBox = function(pBox){
        _pageCol.push(pBox);
    }
    this.init = function(){
        bindingEvent();
        _obj.ActiveStep = 0;
        display(true);
        //起动自动翻页
        startCorss();
    }
}

/**
 * 跳转
 */
Public.GotoUrl = function(url){
    window.location.href = url;
}

/**
 * 表格搜索
 */
Public.TableSearch = function(table, keyword){
    if (keyword) {
        keyword = keyword.replace(/\s+/g, '');
    }
    
    if (!keyword) {
        $('tr', table).each(function(){
            $(this).show();
        });
        return;
    }
    
    var pattern = new RegExp(keyword), is_show = false, is_td = false, str = '';
    $('tr', table).each(function(){
        is_show = false;
        is_td = false;
        
        $('td', this).each(function(){
            is_td = true;
            str = $(this).text().replace(/\s+/g, '');
            if (pattern.test(str)) {
                is_show = true;
            }
        });
        
        if (is_td) {
            if (is_show) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        }
    });
}



Public.Config = {
    //遮罩层背景颜色
    Screen_Background: "#999",
    //遮罩层透明度
    Screen_Opacity: "2",
    //遮罩层内容背景颜色
    Screen_ContentBg: "transparent",
    Screen_PositionTop:"0",
    Screen_PositionLeft:"50%"
}
/*
* 弹出层
*/
Public.ScreenManager = {
    //获取滚动条高度
    GetScrollTop:function(){
        var scrollTop=0;
        if(document.documentElement&&document.documentElement.scrollTop){
            scrollTop=document.documentElement.scrollTop;
        }else if(document.body){
            scrollTop=document.body.scrollTop;
        }
        return scrollTop;
    },
    /*Public 隐藏方法*/
    Hide: function(doFun){
        this.canClose = true;
        this.popCoverDiv(false);
        if(doFun){
            doFun();
        }
    },
    /*Public 显示方法*/
    Show: function(containBox,isClickHide){
        if(isClickHide != undefined){
            Public.ScreenManager.IsClickHide = isClickHide;
        }
        else{
            Public.ScreenManager.IsClickHide = false;
        }
        Public.ScreenManager.setMiddle(containBox);
        this.popCoverDiv(true,containBox);
    },
    //取得页面的高宽
    getBodySize: function (){
        var bodySize = [];
        with(document.documentElement) {
            bodySize[0] = (scrollWidth>clientWidth)?scrollWidth:clientWidth;//如果滚动条的宽度大于页面的宽度，取得滚动条的宽度，否则取页面宽度
            bodySize[1] = (scrollHeight>clientHeight)?scrollHeight:clientHeight;//如果滚动条的高度大于页面的高度，取得滚动条的高度，否则取高度
        }
        return bodySize;
    },
    //弹出框居中显示 add:zen
    setMiddle:function(containBox){
        if(isIE6){
            with (document.documentElement) {
                var tops=Public.ScreenManager.GetScrollTop()+85;
            }
            containBox.style.top=tops+"px";
        }else{
            containBox.style.position="fixed";
        }
        return containBox;
    },
    config:{
        cachebox:"screen_cache_box",/*缓存层*/
        contentbox:"screen_content_box",/*内容层*/
        coverbox:"screen_cover_div",/*透明层*/
        gonebox:"screen_gone_box"	/*移位缓存层*/
    },
    canClose:true,
    ShowSelfControl:function(containBox,showFun){
        Public.ScreenManager.IsClickHide = true;
        this.popCoverDiv(3,containBox,undefined,showFun);
    },
    //创建遮盖层
    popCoverDiv: function (isShow,containBox,setWidth,showFun){
        var screenBox = document.getElementById(Public.ScreenManager.config.coverbox);
        if (!screenBox) {
            //如果存在遮盖层，则让其显示
            //否则创建遮盖层
            var coverDiv = document.createElement('div');
            document.body.appendChild(coverDiv);
            coverDiv.id = Public.ScreenManager.config.coverbox;
            var bodySize;
            with(coverDiv.style) {
                if ($.browser.msie && $.browser.version == 6) {
                    position = 'absolute';
                    background = Public.Config.Screen_Background;
                    left = '0px';
                    top = '0px';
                    bodySize = this.getBodySize();
                    width = '100%';
                    height = bodySize[1] + 'px';
                }
                else{
                    position = 'fixed';
                    background = Public.Config.Screen_Background;
                    left = '0';
                    top = '0';
                    width = '100%'
                    height = '100%';
                }
                zIndex = 99;
                if (document.all) {
                    filter = "Alpha(Opacity=" + Public.Config.Screen_Opacity + "0)";	//IE逆境
                } else {
                    opacity = Number("0."+Public.Config.Screen_Opacity);
                }
            }
            coverDiv.onclick = function(){
                if(Public.ScreenManager.canClose){
                    if(Public.ScreenManager.IsClickHide == undefined || Public.ScreenManager.IsClickHide == false){
                        //coverDiv.style.display = "none";
                        //document.getElementById(Public.ScreenManager.config.contentbox).style.display = "none";
						Public.ScreenManager.Hide();
                    }
                }
            };

            var contentDiv = document.createElement("div");
            contentDiv.id = Public.ScreenManager.config.contentbox;
            with(contentDiv.style){
                position = "absolute";
                backgroundColor = Public.Config.Screen_ContentBg;
                var widthNum = Number(setWidth != undefined?setWidth:500);
                width = widthNum + "px";
                left = Public.Config.Screen_PositionLeft;
                var mfNum = widthNum/2;
                marginLeft = "-" + mfNum + 'px';
                top = Public.Config.Screen_PositionTop;
                zIndex = 100;
            }
            document.body.appendChild(contentDiv);
            contentDiv.onmouseover = function(){
                Public.ScreenManager.canClose = false;
            };

            contentDiv.onmouseout = function(){
                Public.ScreenManager.canClose = true;
            };
            screenBox = contentDiv;
        }
        screenBox.style.display = isShow ? "block" : "none" ;
        if(isShow == 3){
            if(showFun){
                showFun();
            }
        }
        else{
            document.getElementById(Public.ScreenManager.config.contentbox).style.display = isShow ? "block" : "none" ;
            if(isShow && containBox){
                //创建Cache Box
                var cacheBox = document.getElementById(Public.ScreenManager.config.cachebox);
                if(!cacheBox){
                    var cBox = document.createElement("div");
                    document.body.appendChild(cBox);
                    cBox.id = Public.ScreenManager.config.cachebox;
                    cBox.style.display = "none";
                    cacheBox = cBox;
                }

                var goneBox = document.getElementById(Public.ScreenManager.config.gonebox);
                if(!goneBox){
                    var gBox = document.createElement("div");
                    document.body.appendChild(gBox);
                    gBox.id = Public.ScreenManager.config.gonebox;
                    gBox.style.display = "none";
                    goneBox = cBox;
                }

                var cBox = document.getElementById(Public.ScreenManager.config.contentbox);
                var contentNodes = cBox.childNodes;
                for(var i = 0,len = contentNodes.length; i < len; i++){
                    cacheBox.appendChild(contentNodes[i]);
                }
                containBox.style.display = "";
                cBox.appendChild(containBox);
            }
        }
		var hide_tags = ["select","iframe"];
		if(isShow){
			for(var iN = 0,Nlen = hide_tags.length; iN < Nlen; iN++){
				var selList = document.getElementsByTagName(hide_tags[iN]);
				for(var i = 0,len = selList.length; i < len; i++){
					selList[i].style.visibility = "hidden";
				}
				selList = containBox.getElementsByTagName(hide_tags[iN]);
				for(var i = 0,len = selList.length; i < len; i++){
					selList[i].style.visibility = "";
				}
			}
		}
		else{
			for(var iN = 0,Nlen = hide_tags.length; iN < Nlen; iN++){
				var selList = document.getElementsByTagName(hide_tags[iN]);
				for(var i = 0,len = selList.length; i < len; i++){
					selList[i].style.visibility = "";
				}
			}
		}
        this.canClose = true;
    }
}
/*
底部导航
*/
Public.Nav=function(){
    document.write('<div class="box-hd"><h3 class="box-t-l">工具导航</h3><a href="/catalog.html" target="_blank" class="box-t-link" >更多</a></div><dl class="tool_map"><dt>生活指南：</dt><dd class="clearfix"><span><a target="_blank" href="/tianqi/" class="red">天气预报</a></span><span><a target="_blank" href="/live/huoche/" class="green">列车时刻表</a></span><span><a target="_blank" href="/live/speed/">网速测试</a></span><span><a target="_blank" href="/shouji/" class="green">手机号码查询</a></span><span><a target="_blank" href="/youbian/">邮编区号</a></span><span><a target="_blank" href="/live/idcard/">身份证查询</a></span><span><a target="_blank" href="/live/fanyi/">在线翻译</a></span><span><a target="_blank" href="/finance/rate/" class="red">汇率查询</a></span><span><a target="_blank" href="/live/calendar/" class="green">万年历</a></span><span><a target="_blank" href="/live/nongli/">黄道吉日</a></span><span><a target="_blank" href="/live/qqtouxiang/" class="red">QQ头像</a></span><span><a target="_blank" href="/live/nannv/" class="green">生男生女</a></span><span><a target="_blank" href="/live/express/">快递查询</a></span><span><a target="_blank" href="/ip/">IP地址</a></span></dd></dl><dl class="tool_map even"><dt>站长工具：</dt><dd class="clearfix"><span><a target="_blank" href="/siteall/" class="green">综合查询</a></span><span><a target="_blank" href="/record/" class="red">网站收录</a></span><span><a target="_blank" href="/alexa/" class="green">Alexa排名</a></span><span><a target="_blank" href="/pr/">PR值查询</a></span><span><a target="_blank" href="/link/" class="red">友情链接查询</a></span><span><a target="_blank" href="/sitespeed/">网站反应速度</a></span></dd></dl><dl class="tool_map" style="border:none;"><dt>转换工具：</dt><dd class="clearfix"><span><a target="_blank" href="/site/utf8/" class="green">UTF-8转换</a></span><span><a target="_blank" href="/site/html2ubb/" class="green">HTML/UBB互转</a></span><span><a target="_blank" href="/site/html2js/">HTML/JS互转</a></span><span><a target="_blank" href="/site/htmlformat/">JS格式化</a></span><span><a target="_blank" href="/site/regular/">正则表达式</a></span><span><a target="_blank" href="/site/effect/" class="red">多彩字生成</a></span></dd></dl>');
}
//动态加载脚本
Public.GetTextWithScript=function(url,callback){
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src=url;
    script.onload=script.onreadystatechange=function(){
        if(!this.readyState||this.readyState == "loaded" || this.readyState == "complete"){
            if(callback){
                callback();
            }
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    }
    head.appendChild(script);
}

var Handle_Bar_Search_URL;
var HandlerBarCopyHandler;

var ShowDelBtn = function(pToolId){
    var r = Public.MyTools.IsExist(pToolId);
    if(Public.MyTools.IsExist(pToolId) != "-1"){
        $("#js_handle_dele").show();
        $("#js_handle_add").hide();
    }
    else{
        $("#js_handle_dele").hide();
        $("#js_handle_add").show();
    }
}

var HandlerBarAddBtn = function(pText,pStyle,pFun){
    $("#js_handler_bar_list_box").append('<a class="pr5" href="javascript://" onclick="' + pFun + '">'+pText+'</a><a class="'+pStyle+'" href="javascript://" title="'+pText+'"></a>')
}

var HandlerBarCopyLocation = function(){
    if(HandlerBarCopyHandler){
        HandlerBarCopyHandler();
    }
    Public.Copy(Handle_Bar_Search_URL,'地址已复制到剪切板！');
}


//全局 google 关键词
var googleHot=function(){
    var iframe=$('<iframe src="/static/mm/google_950.html" frameborder="0" scrolling="no" width="948px" height="42px" style="margin:4px auto 0;border:1px solid #B9D5E1;" ></iframe>');
    //$("#header").append(iframe);
}




//通用点击115收藏夹脚本
var favTo115=function(){
    var ww = 600,
        wh = 480,
        sl = (window.screen.width - ww) / 2,
        st = (window.screen.height - wh) / 2,
        title=document.title,
        url=document.location.href,
        e=encodeURIComponent;
    window.open('http://sc.115.com/add?from=webpopup&title='+e(title)+'&url='+e(url),'_blank','width=' + ww + ',height=' + wh + ',toolbar=no,menubar=no,status=no,location=no,resizable=yes,left=' + sl + ',top=' + st);
}

